package com.warski.wonderfires.page.music;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.warski.wonderfires.R;
import com.warski.wonderfires.TheApplication;
import com.warski.wonderfires.dlna.DLNAManager;
import com.warski.wonderfires.model.MusicItemInfo;
import com.warski.wonderfires.model.SongListItemInfo;
import com.warski.wonderfires.media.MusicPlayer;
import com.warski.wonderfires.net.JsonStep;
import com.warski.wonderfires.net.TCPConn;
import com.warski.wonderfires.utils.FileUtils;
import com.warski.wonderfires.utils.Logger;
import com.warski.wonderfires.utils.json.JsonUtils;
import com.warski.wonderfires.utils.task.BasicTask;
import com.warski.wonderfires.utils.task.TaskUtils;
import com.warski.wonderfires.view.RoundImageView;
import com.warski.wonderfires.view.TitleBarView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

import static com.warski.wonderfires.TheApplication.mActivity;

/**
 * Created by xuhaiping on 2020/8/30.
 * 播放页面
 */
public class MusicFragment extends Fragment implements MusicPlayer.MusicPlayerListener {
    private TextView nameView;
    private TextView authorView;
    private SeekBar musicTimeBar;
    private ImageView playModeView;
    private ImageView prevMusicView;
    private ImageView nextMusicView;
    private ImageView playMusicView;
    private TextView nowTimeView;
    private TextView fullTimeView;
    private static LrcView lrcView = null;
    private static ILrcBuilder builder;
    private static List<Long> timeList = new ArrayList<>();
    private static List<String> contentList = new ArrayList<>();

    private SongListItemInfo currentSongList = null;
    private TaskUtils taskUtils;
    private boolean userTracking = false;
    private Handler timeUpdateHandler;
    private SongListAdaopter adapter;

    public static void setMusicLrc(InputStream inputStream) {
        String lrc = analyseLyricFile(inputStream);
        List<LrcRow> rows = builder.getLrcRows(lrc);
        lrcView.setLrc(rows);
    }

    private class TimeUpdateTask extends BasicTask {
        public String getName() {
            return "时间刷新任务";
        }

        public void exec() {
            queryPosition();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_music, container, false);

        builder = new DefaultLrcBuilder();
        initSongList(root);
        initTitleBar(root);
        if(MusicPlayer.isPlaying() && mTimer == null){
            mTimer = new Timer();
            mTask = new LrcTask();
            mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
        }

        return root;
    }
    private void initSongList(View root) {
        adapter = new SongListAdaopter(root.getContext());

        ImageView listView = root.findViewById(R.id.musiclist);
        listView.setImageResource(R.mipmap.list);
        listView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindow();
                popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
            }
        });

    }

    private PopupWindow popupWindow;
    private int mPlayerTimerDuration = 100;
    /***
     * 获取PopupWindow实例
     */
    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    /**
     * 创建PopupWindow
     */
    protected void initPopuptWindow() {

        // 获取自定义布局文件pop.xml的视图
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_bottom, null,
                false);
        // 创建PopupWindow实例,2/3屏幕宽度和全屏幕高度
        ListView songList = popupWindowView.findViewById(R.id.song_list);

        songList.setAdapter(adapter);
        songList.setOnItemClickListener((parent, view, position, id) -> {

            if (currentSongList == null){
                String toJson = JsonUtils.toJson(adapter.getItem(0));
                currentSongList = JsonUtils.fromJson(toJson,SongListItemInfo.class);
            }

            MusicItemInfo musicItemInfo = currentSongList.getMusicList().get(position);
            String lrcName = musicItemInfo.getLrc();
//                String lrc = getFromAssets(lrcName);
            InputStream inputStream = FileUtils.readAssetAsInputStream(lrcName);
            String lrc = analyseLyricFile(inputStream);
            List<LrcRow> rows = builder.getLrcRows(lrc);
            lrcView.setLrc(rows);
            MusicPlayer.setCurrentMusicIndex(position);
            // 重新设置歌词
            MusicPlayer.play(currentSongList);
            if(mTimer == null){
                mTimer = new Timer();
                mTask = new LrcTask();
                mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
            }
//                setLrcView();
            popupWindow.dismiss();
        });

        popupWindow = new PopupWindow(popupWindowView, TheApplication.width, TheApplication.height *3/4, true);
        // 设置动画效果
        popupWindow.setAnimationStyle(R.style.AnimationUpDown);
        popupWindow.setOutsideTouchable(true);
        //点击其他地方消失
        popupWindow.setFocusable(true);

    }
    /**
     * 展示歌曲的定时任务
     */
    private Timer mTimer;
    private TimerTask mTask;
    class LrcTask extends TimerTask {
        @Override
        public void run() {
            //获取歌曲播放的位置
            final long timePassed = MusicPlayer.getCurrentPosition();
            mActivity.runOnUiThread(() -> {
                //滚动歌词
                lrcView.seekLrcToTime(timePassed);
            });

        }
    };

    @Override
    public void onResume() {
        TCPConn.getInstance().sendData(JsonStep.FireOpen.getJsonString());
        super.onResume();
    }

    @Override
    public void onPause() {
        if (MusicPlayer.isDlnaRunning()) {
            MusicPlayer.stop();
        }
        TCPConn.getInstance().sendData(JsonStep.FireLevelMinSet.getJsonString());
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        MusicPlayer.setListener(null);
        taskUtils.shutdown();
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroyView();
    }


    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        try {
            initControl();
            updateView();

        } catch (Exception e) {
            Logger.error(e);
        }
    }
    public static String analyseLyricFile(InputStream inputStream){ //参数是歌词文件的路径

        BufferedReader reader = null;
        timeList.clear();
        contentList.clear();
        InputStreamReader inputFileReader;
        String tempString;
        //正则表达式解析出时间戳
        String result = "";
        try {
            inputFileReader = new InputStreamReader(inputStream, "GB2312");
            reader = new BufferedReader(inputFileReader);
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                if(tempString.trim().equals(""))
                    continue;
                result += tempString + "\r\n";
            }

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return result;
    }

    private void initTitleBar(View root) {
        final TitleBarView titleBarView = root.findViewById(R.id.titlebar);
        if (MusicPlayer.isDlnaAvailable() && MusicPlayer.isDlnaRunning()) titleBarView.setLeftIcon(R.mipmap.soundbox_connected);
        else titleBarView.setLeftIcon(R.mipmap.device);
        titleBarView.setRightIconOnClickListener(v ->
                Toast.makeText(mActivity.getApplicationContext(),"在线音乐播放，由ios开发",Toast.LENGTH_SHORT).show());

        titleBarView.setLeftIconOnClickListener(v -> {
            if (!MusicPlayer.isDlnaAvailable()) {
                NavHostFragment
                        .findNavController(MusicFragment.this)
                        .navigate(R.id.action_MusicFragment_to_SearchDeviceFragment);

            } else {
                int leftIcon = titleBarView.getLeftIcon();

                if(leftIcon != R.mipmap.soundbox_connected) {
                    NavHostFragment
                            .findNavController(MusicFragment.this)
                            .navigate(R.id.action_MusicFragment_to_SearchDeviceFragment);
                    /*new AlertDialog.Builder(root.getContext())
                            .setTitle(R.string.dlna_play_music)
                            .setMessage(R.string.dlna_push_to_device_start)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    MusicPlayer.startDlna();
                                    titleBarView.setLeftIcon(R.mipmap.soundbox_connected);
                                }
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();*/
                } else{
                    new AlertDialog.Builder(root.getContext())
                            .setTitle(R.string.dlna_play_music)
                            .setMessage(R.string.dlna_push_to_device_end)
                            .setPositiveButton(R.string.yes, (dialog, which) -> {
                                DLNAManager.disconnectDevice();
                                MusicPlayer.stopDlna();
                                titleBarView.setLeftIcon(R.mipmap.device);
                            })
                            .setNegativeButton(R.string.no, null)
                            .show();
                }
            }
        });

    }

    private void initControl() {
        nameView = this.getView().findViewById(R.id.musicname);
        authorView = this.getView().findViewById(R.id.musicauthor);
        lrcView = this.getView().findViewById(R.id.lyric_show);
        lrcView.setBackgroundResource(R.mipmap.fire_bg);
        lrcView.setListener(new ILrcViewListener() {
            //当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
            public void onLrcSought(int newPosition, LrcRow row) {
                if (MusicPlayer.isPlaying()) {
                    MusicPlayer.seekTo((int) row.startTime);
                }
            }
        });
        musicTimeBar = this.getView().findViewById(R.id.musictimebar);
        playModeView = this.getView().findViewById(R.id.playmode);
        playModeView.setImageResource(R.mipmap.play_loop);
        prevMusicView = this.getView().findViewById(R.id.prevmusic);
        prevMusicView.setImageResource(R.mipmap.prev_music);
        nextMusicView = this.getView().findViewById(R.id.nextmusic);
        nextMusicView.setImageResource(R.mipmap.next_music);
        playMusicView = this.getView().findViewById(R.id.playmusic);
        playMusicView.setImageResource(R.mipmap.play);
        nowTimeView = this.getView().findViewById(R.id.nowtime);
        fullTimeView = this.getView().findViewById(R.id.fulltime);

        playModeView.setOnClickListener(v -> {
            switch (MusicPlayer.getMode()) {
                case Normal:
                    MusicPlayer.setMode(MusicPlayer.PlayModeType.Random);
                    break;
                case Random:
                    MusicPlayer.setMode(MusicPlayer.PlayModeType.Normal);
                    break;
                default: break;
            }
            updateView();
        });
        prevMusicView.setOnClickListener(v -> {
            if (currentSongList != null){
                MusicPlayer.playPrev();
                updateView();
            }else {
                String toJson = JsonUtils.toJson(adapter.getItem(0));
                currentSongList = JsonUtils.fromJson(toJson,SongListItemInfo.class);
                MusicItemInfo musicItemInfo = currentSongList.getMusicList().get(0);
                String lrcName = musicItemInfo.getLrc();
                InputStream inputStream = FileUtils.readAssetAsInputStream(lrcName);
                String lrc = analyseLyricFile(inputStream);
                List<LrcRow> rows = builder.getLrcRows(lrc);
                //将得到的歌词集合传给mLrcView用来展示
                lrcView.setLrc(rows);
                MusicPlayer.setCurrentMusicIndex(currentSongList.getMusicList().size()-1);
                MusicPlayer.play(currentSongList);
                updateView();
                if(mTimer == null){
                    mTimer = new Timer();
                    mTask = new LrcTask();
                    mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
                }
            }
        });
        nextMusicView.setOnClickListener(v -> {
            if (currentSongList != null){
                MusicPlayer.playNext();
                updateView();
            }else {
                String toJson = JsonUtils.toJson(adapter.getItem(0));
                currentSongList = JsonUtils.fromJson(toJson,SongListItemInfo.class);
                MusicItemInfo musicItemInfo = currentSongList.getMusicList().get(0);
                String lrcName = musicItemInfo.getLrc();
                InputStream inputStream = FileUtils.readAssetAsInputStream(lrcName);
                String lrc = analyseLyricFile(inputStream);
                List<LrcRow> rows = builder.getLrcRows(lrc);
                //将得到的歌词集合传给mLrcView用来展示
                lrcView.setLrc(rows);
                MusicPlayer.setCurrentMusicIndex(1);
                MusicPlayer.play(currentSongList);
                updateView();
                if(mTimer == null){
                    mTimer = new Timer();
                    mTask = new LrcTask();
                    mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
                }
            }
        });
        playMusicView.setOnClickListener(v -> {
            if (MusicPlayer.isPlaying()) {
                MusicPlayer.pause();
            } else {
                if (currentSongList == null){
                    String toJson = JsonUtils.toJson(adapter.getItem(0));
                    currentSongList = JsonUtils.fromJson(toJson,SongListItemInfo.class);
                    MusicItemInfo musicItemInfo = currentSongList.getMusicList().get(0);
                    String lrcName = musicItemInfo.getLrc();
                    InputStream inputStream = FileUtils.readAssetAsInputStream(lrcName);
                    String lrc = analyseLyricFile(inputStream);
                    List<LrcRow> rows = builder.getLrcRows(lrc);
                    //将得到的歌词集合传给mLrcView用来展示
                    lrcView.setLrc(rows);
                    MusicPlayer.setCurrentMusicIndex(0);
                    MusicPlayer.play(currentSongList);
                }else {
                    MusicPlayer.play();
                }
            }
            if(mTimer == null){
                mTimer = new Timer();
                mTask = new LrcTask();
                mTimer.scheduleAtFixedRate(mTask, 0, mPlayerTimerDuration);
            }
            updateView();
        });
        musicTimeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    MusicPlayer.seekTo(progress * 1000);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                userTracking = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                userTracking = false;
            }
        });

        timeUpdateHandler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    updateMusicTime((int) msg.obj);
                }
            }

        };

        taskUtils = new TaskUtils();
        taskUtils.loopTask(new TimeUpdateTask(), 1);
        MusicPlayer.setListener(this);
    }

    public void updateView() {
        MusicItemInfo musicInfo = MusicPlayer.getCurrentMusic();

        if (musicInfo != null){
            nameView.setText(musicInfo.getName());
            authorView.setText(musicInfo.getAuthor());
        }

        switch (MusicPlayer.getMode()) {
            case Normal:
                playModeView.setImageResource(R.mipmap.play_loop);
                break;
            case Random:
                playModeView.setImageResource(R.mipmap.play_random);
                break;
        }

        if (MusicPlayer.isPlaying()) {
            playMusicView.setImageResource(R.mipmap.pause);
        } else {
            playMusicView.setImageResource(R.mipmap.play);
        }

        int length = MusicPlayer.getLength() / 1000;
        musicTimeBar.setMax(length);
        fullTimeView.setText(String.format("%02d:%02d", length / 60, length % 60));

        queryPosition();
    }

    private void queryPosition() {
        if (!userTracking) {
            MusicPlayer.queryPosition();
        }
    }

    private void updateMusicTime(int msec){
        int position = msec / 1000;
        musicTimeBar.setProgress(position);
        nowTimeView.setText(String.format("%02d:%02d", position / 60, position % 60));
    }

    public void onMusicChanged() {
        updateView();
    }

    public void onGetPosition(int msec){
        Message message = new Message();
        message.what = 1;
        message.obj = msec;
        timeUpdateHandler.sendMessage(message);
    }
}
